<template>
    <div class="login_page fillcontain" v-loading="loading">
        <div class="logo-title">
            <div class="mwidth"><img src="../assets/img/logokb.png" /></div>
        </div>
        <transition name="form-fade" mode="in-out">
            <section class="form_contianer" v-show="showLogin">
                <div class="manage_tip">
                    <!-- logo -->
                    <p style="color:#0063be;">SMMS</p>
                </div>
                <el-form :model="loginForm" :rules="rules" ref="loginForm" class="login-form">
                    <el-form-item prop="username">
                        <i class="login-icon icon-3"></i>
                        <el-input v-model="loginForm.username"></el-input><!-- 用户名 -->
                    </el-form-item>
                    <el-form-item prop="password">
                        <i class="login-icon icon-4"></i>
                        <el-input type="password" v-model="loginForm.password"  @keyup.enter.native="submitForm('loginForm')"></el-input><!-- 密码 -->
                    </el-form-item>
                    <el-form-item prop="company">
                        <i class="login-icon icon-5"></i>
                        <el-select v-model="loginForm.company" filterable placeholder=" ">
                            <el-option v-for="item in companyOptions" :key="item.CompanyCode" :label="item.CompanyName" :value="item.CompanyCode">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="language">
                        <i class="login-icon icon-6"></i>
                        <el-select v-model="loginForm.language" filterable @change="changeLanguage" placeholder=" ">
                            <el-option v-for="item in languageOptions" :key="item.CultureCode" :label="item.CultureName" :value="item.CultureCode">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-checkbox v-model="checked" class="remember">{{$t('message.rememberUsername')}}</el-checkbox>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="warning" @click="submitForm('loginForm')" @keyup.enter="submitForm('loginForm')" class="submit_btn">{{$t('message.login')}}</el-button>
                    </el-form-item>
                </el-form>
            </section>
        </transition>
    </div>
</template>

<script>
    // import { login, token, getCompanys, getJsonResource, getlanguage, getLanguageList } from "@/api/getData";
    import { baseUrl, baseImgPath } from "@/config/env";
    import { mapActions, mapState } from "vuex";
    import { ajax, AjaxPOST } from "@/config/fetch";
    import en from './../i18n/langs/en';
    import cn from './../i18n/langs/cn';
    import { setStore, setLocal, getLocal, removeLocal } from "../config/mUtils";
    import "babel-polyfill";
    export default {
        data() {
            return {
                loginForm: {
                    username: getLocal("username") ? getLocal("username") : "",
                    password: "",
                    company: "",
                    language: "en_US"
                },
                companyOptions: [],
                languageOptions: [
                    {
                        CultureName: this.$t('message.chinese'),
                        CultureCode: 'zh_CN'
                    }, {
                        CultureName: this.$t('message.english'),
                        CultureCode: 'en_US'
                    }
                ],
                showLogin: false,
                checked: getLocal("username") ? true : false,
                langs: [],
                loading: false,
            };
        },
        computed: {
            rules: function(){
                return{
                    username: [{
                        required: true,
                        message: "",
                        trigger: "change"
                    }],
                    password: [{
                        required: true,
                        message: "",
                        trigger: "change"
                    }]
                }
            },
            ...mapState(["adminInfo", "en"])
        },
        watch: {
            adminInfo: function (newValue) {
                if (newValue.id) {
                    this.$message({
                        type: "success",
                        message: "检测到您之前登录过，将自动登录"
                    });
                    this.$router.push("manage");
                }
            },
        },
        created() {
            this.loginForm.language = getLocal('language');
            // this.getLanguageResource();
            // this.languageList();
            // this.getCompanyList();
        },
        mounted() {
            this.showLogin = true;
            if (!this.adminInfo.id) {
                // this.getAdminData();
            }
            $(function(){
                $(".el-dialog").draggable({ handle: ".el-dialog__header" }); //使用jqueryui中的拖拽实现模态框的拖动
            });
        },
        methods: {
            ...mapActions(["getAdminData"]),
            async submitForm(formName) {
                /*this.$refs[formName].validate(async valid => {
                    if (valid) {
                        if (this.checked) {
                            setLocal("username", this.loginForm.username);
                        } else {
                            removeLocal("username");
                        }
                        let tokenurl = baseUrl + "/token";
                        let elem = this;
                        let parm="&grant_type=password&username=" + Base64.encode(this.loginForm.username +","+this.loginForm.company+",IsHR")+
                           "&password=" + Base64.encode(this.loginForm.password);
                            elem.loading = true;
                        ajax({
                            url: tokenurl,
                            type: "POST",
                            contentType: "application/json;",
                            data: parm,
                            success: function (res) {
                               //elem.loading = false;
                                if (res.access_token) {
                                    elem.$message({
                                        type: "success",
                                        message: elem.$t('message.LogonSuccess')
                                    });
                                    setStore("token", res.access_token);
                                    setStore("LoginName", res.LoginName);
                                    setStore("Name", res.Name);
                                    setStore("CompanyCode", res.CompanyCode);
                                    setStore("CompanyName", res.CompanyName);
                                    setStore("CompanyEnName", res.CompanyEnName);
                                    setStore("CulutreCode", res.CulutreCode);
                                    setStore("refresh_token", res.refresh_token);
                                    setStore("Id", res.Id);
                                    setStore("ManageCompany", res.ManageCompany);
                                    setStore("IKYCZ", res.IKYCZ);
                                    setStore("NameFormat", res.NameFormat);
                                    setStore("IsShowPrivacy", res.IsShowPrivacy);
                                    elem.$router.push("manage");
                                } else {
                                    elem.loading = false;
                                    elem.$message({
                                        type: "error",
                                        message: res.Message
                                    });
                                }
                            },
                            error:function(res) {
                                // res = JSON.parse(res);
                                elem.$message({
                                        type: "error",
                                        message: res.error_description
                                });
                                elem.loading = false;
                            }
                        });
                    } else {
                        console.log(this.langs);
                        this.loading = false;
                        this.$message.error({
                            title: "错误",
                            message:  this.langs.LogonError,//"请输入正确的用户名密码",
                            offset: 100
                        });
                        return false;
                    }
                });*/
                setStore("Name", '超级管理员');
                this.$router.push("manage");
            },
            changeLanguage() {
                this.getLanguageResource();
                setLocal('language', this.loginForm.language);
                if (getLocal('language') == 'zh_CN') {
                    this.$i18n.locale = "cn";
                } else if (getLocal('language') == 'en_US') {
                    this.$i18n.locale = "en";
                } else {
                    this.$i18n.locale = "cn";
                }
            },
            async getLanguageResource() {
                const crs = await getJsonResource();
                if (crs.Flag) {
                    this.loading=false;
                    cn.message = Object.assign(cn.message, crs.Result.zh_CN);
                    en.message = Object.assign(en.message, crs.Result.en_US);
                    if (getLocal('language') === 'zh_CN') {
                        this.$i18n.locale = "cn";
                        this.langs= cn.message;
                        this.rules.username[0].message = cn.message.username;
                        this.rules.password[0].message = cn.message.password;
                    } else if (getLocal('language') === 'en_US') {
                        this.$i18n.locale = "en";
                        this.langs=en.message;
                        this.rules.username[0].message = en.message.username;
                        this.rules.password[0].message = en.message.password;
                    } else {
                        this.$i18n.locale = "cn";
                        this.langs=cn.message;
                    }
                }
            },
            async languageList() {
                // debugger;
                const crs = await getlanguage({});
                if (crs.Flag) {
                    this.languageOptions = crs.Result;
                }
            },
            async getCompanyList() {
                const crs = await getCompanys({
                    CompanyCode: "",
                    CompanyName: "",
                    PageSize: 20,
                    PageIndex: 1
                });
                if (crs.Flag) {
                    this.companyOptions = crs.Result.rows;
                    if (this.companyOptions.length>0) {
                        if (sessionStorage.getItem('CompanyCode') === "" || sessionStorage.getItem('CompanyCode') === null || sessionStorage.getItem('CompanyCode') === undefined || sessionStorage.getItem('CompanyCode') === 0) {
                            this.loginForm.company = this.companyOptions[0].CompanyCode
                        } else {
                            this.loginForm.company = sessionStorage.getItem("CompanyCode")
                        }
                    } else {
                        this.loginForm.company = "";
                    }
                }
            },
        }
    };

</script>

<style lang="less" scoped>
    .tip {
        font-size: 12px;
        color: red;
    }

    .form-fade-enter-active,
    .form-fade-leave-active {
        transition: all 1s;
    }

    .form-fade-enter,
    .form-fade-leave-active {
        transform: translate3d(0, -50px, 0);
        opacity: 0;
    }

</style>
